﻿#include "ZFtpResponsePrivate.h"
#include "qftp.h"
#include "ZFtpResponse.h"

BEGIN_NAMESPACE_ZFTPNS

ZFtpResponsePrivate::ZFtpResponsePrivate(QObject *parent) :
    QObject(parent),
    m_task_id(-1)
{
    init();
}

void ZFtpResponsePrivate::listenTo(QSharedPointer<QFtp> ftp, QSharedPointer<ZFtpConfig> cfg)
{
    if (!ftp) return;

    m_current_ftp = ftp;

    ftp->disconnect(this, SLOT(slotFtpCommandStarted(int)));
    ftp->disconnect(this, SLOT(slotFtpCommandFinished(int,bool)));
    connect(ftp.data(), SIGNAL(commandStarted(int)), SLOT(slotFtpCommandStarted(int)));
    connect(ftp.data(), SIGNAL(commandFinished(int,bool)), SLOT(slotFtpCommandFinished(int,bool)));
}

void ZFtpResponsePrivate::setPublicResponseObject(QPointer<ZFtpResponse> response)
{
    if (!response) return;

    // 在此统一将内部信号传递给公开的接口类，而接口类及子类不需要修改代码
    connect(this, SIGNAL(sigRequestQueued()), response.data(), SIGNAL(sigRequestQueued()));
    connect(this, SIGNAL(sigRequestStarted()), response.data(), SIGNAL(sigRequestStarted()));
    connect(this, SIGNAL(sigRequestFinished(bool)), response.data(), SIGNAL(sigRequestFinished(bool)));
}

void ZFtpResponsePrivate::setLastErrorString(const QString &error_string)
{
    m_last_error_string = error_string;
}

void ZFtpResponsePrivate::setFtpTaskID(const int &id)
{
    m_task_id = id;
}

int ZFtpResponsePrivate::ftpTaskID()
{
    return m_task_id;
}

void ZFtpResponsePrivate::invalidFtpTaskID()
{
    m_task_id = InvalidTaskID;
}

bool ZFtpResponsePrivate::isFtpTaskIDValid()
{
    return m_task_id >= 0;
}

QString ZFtpResponsePrivate::lastErrorString()
{
    return m_last_error_string;
}

void ZFtpResponsePrivate::init()
{
    createConnects();
}

void ZFtpResponsePrivate::createConnects()
{
}

void ZFtpResponsePrivate::slotFtpCommandStarted(int id)
{
    if (id != this->ftpTaskID()) return;
    emit sigRequestStarted();
}

void ZFtpResponsePrivate::slotFtpCommandFinished(int id, bool error)
{
    if (id != this->ftpTaskID()) return;
    if (error)
    {
        setLastErrorString(m_current_ftp->errorString());
    }
    else
    {
        setLastErrorString("");
    }

    emit sigRequestFinished(!error);
}

END_NAMESPACE
